<template>
    <div class="listDiv pd20">
        <div class="searchDiv">
            <el-form class="searchLeft" ref="serform" :model="obj.req" label-position="top">
                <el-form-item class="serlabelB mr20 mb10" label="创建时间：" prop="starttime">
                    <DateRange v-model:start="obj.req.starttime" v-model:end="obj.req.endtime"></DateRange>
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="文件名称：" prop="name">
                    <el-input v-model="obj.req.name" placeholder="请输入文件名称" class="search_key" clearable  />
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="文件编号：" prop="code">
                    <el-input v-model="obj.req.code" placeholder="请输入文件编号" class="search_key" clearable />
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="承办单位/人：" prop="userids">
                    <el-cascader v-model="obj.req.userids" :props="getdeptP" placeholder="请选择承办单位/人" clearable :show-all-levels="false" />
                </el-form-item>
                <el-form-item class="serlabelB mr20 mb10" label="关键词：" prop="keyword">
                    <el-input v-model="obj.req.keyword" placeholder="请输入关键词" class="search_key" clearable />
                </el-form-item>
                <span class="btn search mb10 mr5" @click="obj.req.currentpage=1;init()">查询</span>
                <span class="btn refresh mb10 mr5" @click="proxy.$refs['serform'].resetFields();init()">重置</span>
                <span class="btn search mb10" @click="DownExcelExports">批量下载</span>
            </el-form>
        </div>
        <div class="table" id="tb">
            <ul class="head">
                <li class="li30"><el-checkbox v-model="obj.checkAll" :indeterminate="obj.isIndeterminate" @change="handleCheckAllChange"></el-checkbox></li>
                <li class="li100 liflex fixed ls">文件名称</li>
                <li class="li150">文件编号</li>
                <li class="liflex">承办单位</li>
                <li class="liflex">关键词</li>
                <li class="li260">简介</li>
                <li class="litime"><HeadSort text="录入时间" v-model:sort="obj.req.sort" :index="1" @sortClick="obj.req.currentpage=1;init()" /></li>
                <li class="liaction li160">操作</li>
            </ul>
            <div class="body">
                <ul v-for="(x,i) in obj.ary" :key="x">
                    <li class="li30"><el-checkbox v-model="obj.checks[i]" size="large" @change="handleCheck" /></li>
                    <li class="li100 liflex fixed ls"><span class="lineOne">{{x.name}}</span></li>
                    <li class="li150 flex-center"><span class="lineOne">{{x.code}}</span></li>
                    <li class="liflex flex-center">{{x.dept_name}}</li>
                    <li class="liflex flex-center">{{ x.keyword }}</li>
                    <li class="li260">
                        <el-tooltip
                                    class="box-item"
                                    effect="dark" :disabled="x.synopsis.length<19"
                                    :content="x.synopsis"
                                    placement="top-start"
                                >
                                <template #content><div style="width: 600px;">{{ x.synopsis }}</div></template>
                            <span class="lineOne">{{x.synopsis}}</span>
                        </el-tooltip></li>
                    <li class="litime flex-center">{{ x.intime }}</li>
                    <li class="liaction li160 flex-center">
                        <u @click.prevent="edit(x)">编辑</u>
                        <u @click.prevent="read(x)">详情</u>
                        <u @click.prevent="obj.showLog_id=x.file_id;obj.showLog_name=x.name;">日志</u>
                        <u @click.prevent="DownExcelExport('完成文件',[x.file_id])">下载</u>
                        <DelConfirm @yesClick="del(x)" />
                    </li>
                </ul>
            </div>
        </div>
        <ElConfigProvider :locale="locale">
            <el-pagination layout="total, prev, pager, next, jumper" background :total="obj.req.count" :page-size="obj.req.pagesize" v-model:currentPage="obj.req.currentpage" @current-change="init()" />
        </ElConfigProvider>
        <div v-if="obj.showLog_id" class="showLogbox">
            <ReadFileLog :id="obj.showLog_id" :name="obj.showLog_name" :tags="['文件管理','完成文件','承办进展']" @close="obj.showLog_id=false" />
        </div>
    </div>
</template>

<script setup>
    import { reactive,getCurrentInstance,onMounted,onActivated } from 'vue'
    import dayjs from 'dayjs'
    import { Star,StarFilled } from "@element-plus/icons-vue";
    import DelConfirm from '@/components/del_confirm.vue'
    import DateRange from '@/components/date_range.vue'
    import HeadSort from '@/components/head_sort.vue'
    import ReadFileLog from '../readFileLog.vue'

    import locale from "element-plus/es/locale/lang/zh-cn";
    let { proxy } = getCurrentInstance()

    let obj = reactive({
        showLog_id: false,
        showLog_name: '',
        ary:[],
        req:{
            "type": "complete",
            "userid": "",
            userids: [],
            "starttime": "",
            "endtime": "",
            "name": "",
            "code": "",
            "dept_id": "",
            "dept_name": "",
            "company_name": "",
            "user_name": "",
            "keyword": "",
            "sort": "",
            "currentpage": 1,
            "pagesize": 10,
            count: 0,
        },
        companys: [],
        companys: [],
        file_ids: [],
        checks: [],
        checkAll: false,
        isIndeterminate: false
    })

    onActivated(async()=>{
        obj.companys = await proxy.$setting.getdepts()
        init()
    })

    const init=()=>{
        obj.req.dept_id = obj.req.userids&&obj.req.userids.length==1?obj.req.userids[0]:''
        obj.req.userid = obj.req.userids&&obj.req.userids.length>1?obj.req.userids[1]:''
        proxy.$ajax({
            url: '/manager/file/list',
            data: obj.req,
            bfLoading: true
        }).then(d => {
            if(d.success){
                obj.ary = d.msg.list
                obj.req.count = d.msg.count
                obj.checks = new Array(obj.ary.length).fill(false)
            }
        }).catch(() => { })
    }

    const getdeptP = {
        lazy: true,
        checkStrictly: true,
        label:'name', value: 'id',
        async lazyLoad(node, resolve) {
            const { level,value } = node
            setTimeout(async() => {
                if(level==0){
                    const arr = await proxy.$setting.getdepts()
                    resolve(arr)
                }else if(level==1){
                    let arr = await proxy.$setting.getusers(value)
                    arr.map(e=>{
                        e.leaf = true
                    })
                    resolve(arr)
                }else{resolve([])}
            }, 200);
        }
    }

    let edit = x => {
        proxy.routerPushMixin("/comfileEdit",{id:x.file_id,dept_name:x.dept_name,user_name:x.user_name,codetime:x.codetime})
    }

    let read = x => {
        proxy.routerPushMixin("/comfileEdit",{id:x.file_id,dept_name:x.dept_name,user_name:x.user_name,codetime:x.codetime,disabled:true})
    }

    const setjing = (x,text) => {
        proxy.$ajax({
            url: '/manager/file/boutique/complete',
            data: { file_id: x.file_id },
            bfLoading: true
        }).then(d => {
            if(d.success){
                proxy.elMessageMixin(`${text}成功`, 'success')
                init()
            }else{
                proxy.elMessageMixin(d.err, 'error')
            }
        }).catch(() => { })
    }

    let del = x => {
        proxy.$ajax({
            url: '/manager/file/delete',
            data: { file_id: x.file_id },
            bfLoading: true
        }).then(d => {
            if(d.success){
                proxy.elMessageMixin("删除成功", 'success')
                init()
            }else{
                proxy.elMessageMixin(d.err, 'error')
            }
        }).catch(() => { })
    }

    const handleCheckAllChange = (val) => {
        obj.checks = new Array(obj.ary.length).fill(val)
        obj.isIndeterminate = false
    }

    const handleCheck=(val)=>{
        obj.isIndeterminate = obj.checks.some(x=>x) && !obj.checks.every(x=>x)
        obj.checkAll = obj.checks.every(x=>x)
    }

    const DownExcelExports=()=>{
        let file_ids = []
        for (let i = 0; i < obj.ary.length; i++) {
            if (obj.checks[i]){
                file_ids.push(obj.ary[i].file_id)
            }
        }
        DownExcelExport('完成文件',file_ids)
    }

    let get = (file_id) => {
        return new Promise((resolve, reject) => {
            proxy.$ajax({
                url: '/manager/file/get',
                data: { file_id: file_id },
                bfLoading: true
            }).then(d => {
                resolve(d.msg||{})
            }).catch(e => {
                reject({})
            })
        })
    }

    const DownExcelExport=async(typename,ids)=>{
        if(ids.length==0){
            proxy.elMessageMixin("请选择文件", 'error')
            return
        }
        let list = []
        for (let i = 0; i < ids.length; i++) {
            const o = await get(ids[i])
            const listo = obj.ary.find(e => e.file_id == ids[i])
            const item = {
                ...o,
                boutique: o.boutique == 1 ? '是' : '否',
                state: proxy.$setting.globalData.fileStates[o.state||0].name,
                dept_name: listo?listo.dept_name:'',
                user_name: listo?listo.user_name:'',
                imgs: o.imgs?o.imgs.split(',').map(e=>`${proxy.$setting.globalUrl.fileurl}/files/${e}`):'',
                files: o.imgs?o.files.split(',').map(e=>`${proxy.$setting.globalUrl.fileurl}/files/${e}`):'',
                instructions: o.instructions?o.instructions.map((e,i)=>`${e.intime}：${e.msg}${i==o.instructions.length-1?'。':'；'}`):''
            }
            list.push(item)  
        }
        // return
        const fields = [
            'file_id',
            'code',
            'codetime',
            'boutique',//精品文件
            'name',
            // 'category',//类别 0历史文件/1普通文件/3舆情事件
            'state',//办理进度
            'synopsis',
            'keyword',
            'dept_name',//承办单位
            'user_name',//承办人
            'intime',
            'imgs',//图片
            'files',//文件
            'instructions',//首长批示
            'supervise',
            // 'province',
        ]
        const headers = [
            '文件ID',
            '文件编号',
            '编号生成时间',
            '精品文件',//
            '文件名称',
            // '类别',//
            '办理进度',//
            '文件简介',
            '关键词',
            '承办单位',//
            '承办人',//
            '上传时间',
            '图片',//
            '文件',//
            '首长批示',//
            '督办情况',
            // '省份信息',
        ]
        proxy.$util.ExcelExport(list, fields, headers, `${typename}-${dayjs().format('YYYYMMDDHHmmss')}`, 'Sheet', null, [], true)
    }
</script>

<style scoped>
</style>